<template>
  <view>
    <!-- 引入返回导航栏组件 -->
    <back-bar :backTitle="backTitle"></back-bar>
    
    <view class="box">
      <!-- 筛选器 -->
      <picker mode="selector" :range="filterOptions" :value="filterIndex" @change="handleFilterChange">
        <view class="picker">
          {{ filterOptions[filterIndex] }}
        </view>
      </picker>
      <!-- 发票抬头按钮 -->
      <!-- <text @tap="goToInvoiceTitle" class="invoice-title-btn">发票抬头</text> -->
    </view>

    <!-- 滚动容器 -->
    <view class="scroll-container">
      <view class="box1">
        <checkbox-group @change="handleCheckGroupChange">
          <view class="list" v-for="(item, index) in invoiceList" :key="item.id" :class="{ 'selected': item.checked }">
            <view class="left">
              <view class="img">
                <image src="../../../static/tabBar/item12.png" mode="aspectFit"></image>
              </view>
              <view class="text">
                <view class="p1">{{ item.createTime}}</view>
                <view class="p2">
                  <view>￥{{ item.totalAmount }}</view>
                  <view>
                    <image src="../../../static/tabBar/wxzf.png" mode="aspectFit"></image>
                  </view>
                </view>
                <view class="p3">交易单号：{{ item.outTradeNo }}</view>
              </view>
            </view>
            <view class="right">
              <checkbox :value="item.id" :checked="item.checked"></checkbox>
            </view>
          </view>
        </checkbox-group>
      </view>
    </view>

    <!-- 分页组件 -->
    <view class="pagination-container">
      <uni-section title="开票记录" type="line" padding>
        <uni-pagination :show-icon="true" :total="totalCount" :pageSize="pageSize" @change="handlePageChange" />
      </uni-section>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom">
      <!-- <view class="p1">
        <view :class="{ selected: selectedStatus === '未开票' }" @tap="changeStatus('未开票')">未开票</view>
        <view :class="{ selected: selectedStatus === '已开票' }" @tap="changeStatus('已开票')">已开票</view>
      </view> -->
      <view class="p2">
        <view class="left">
          <view @tap="selectAll">
            <view v-show="!allChecked">本页全选</view>
            <view v-show="allChecked">取消全选</view>
          </view>
        </view>
        <view class="button" @tap="submitInvoice">提交开票</view>
      </view>
    </view>
  </view>
</template>

<script>
import { invoiceDaikai, invoiceIssue } from '@/api/parking.js';
export default {
  data() {
    return {
      backTitle: '电子发票',
      filterOptions: ['全部订单', '停车费'],
      filterIndex: 0,
      // selectedStatus: '未开票',
      allChecked: false,
      invoiceList: [],
      currentPage: 1,
      pageSize: 5,
      totalCount: 0,
      selectedInvoice: null
    };
  },

  onLoad() {
    this.getInvoiceList();
  },

  methods:{
    // 处理筛选器变化
    handleFilterChange(e) {
      this.filterIndex = e.detail.value;
      this.currentPage = 1;
      this.getInvoiceList();
    },
    
    // 前往发票抬头设置
    goToInvoiceTitle() {
      uni.navigateTo({
        url: '/pages/invoice-title/index'
      });
    },
    
    // 获取开票记录
    getInvoiceList() {
      const openid = uni.getStorageSync('openid');
      if (openid) {
        let params = {
          openid: openid,
          pageNum: this.currentPage,
          pageSize: this.pageSize
        }
        
        invoiceDaikai(params)
          .then(res => {
            const data = res || {};
            this.invoiceList = data.records ||data.rows || [];
            this.totalCount = data.total || 0;
            
            // 初始化勾选状态
            this.invoiceList.forEach(item => {
              item.checked = false;
            });

            console.log('获取开票记录:', res);
            // console.log('获取开票记录totalPages:', this.totalPages );
          })
          .catch(err => {
            console.error('获取开票记录失败:', err);
            uni.showToast({
              title: '获取开票记录失败',
              icon: 'none'
            });
          });
      } else {
        console.error('未获取到openid');
        uni.showToast({
          title: '未获取到openid，请重新登录',
          icon: 'none'
        });
      }
    },
    
    // 处理分页变化
    handlePageChange(e) {
      this.currentPage = e.currentPage;
      this.getInvoiceList();
    },
    
    // 切换开票状态
    changeStatus(status) {
      this.selectedStatus = status;
      this.currentPage = 1;
      this.getInvoiceList();
    },
    
    // 全选/取消全选
    selectAll() {
      this.allChecked = !this.allChecked;
      this.invoiceList.forEach(item => {
        item.checked = this.allChecked;
      });
    },
    
    // 处理单个复选框变化
    handleSingleCheckChange(item, event) {
      console.log('点击选择');
      // item.checked = event.detail.value.includes(item.id);
      // this.allChecked = this.invoiceList.every(item => item.checked);
      // console.log('点击开票：',item);
    },
    
    // 处理复选框组变化
    handleCheckGroupChange(e) {
      console.log('点击选择组',e);
      const selectedIds = e.detail.value;
      this.invoiceList.forEach(item => {
      
        item.checked = selectedIds.includes(String(item.id));
      });
      this.allChecked = selectedIds.length === this.invoiceList.length;
      console.log('当前选中项', selectedIds);
      console.log('当前选中项this.invoiceList', this.invoiceList);
    },
    
    // 提交开票
    submitInvoice() {
      const selectedItems = this.invoiceList.filter(item => item.checked);
      
      if (selectedItems.length === 0) {
        uni.showToast({
          title: '请选择要开票的记录',
          icon: 'none'
        });
        return;
      }
      
      // 弹出提示：信息会保留180天，系统升级中
      uni.showModal({
        title: '提示',
        content: '信息会保留180天,系统升级中',
        showCancel: false,
        success: () => {
          // 提示关闭后执行开票逻辑
          // selectedItems.forEach(item => {
          //   let params = {
          //     orderSn: item.outTradeNo,
          //     amount: item.totalAmount,
          //     remark: '停车费'
          //   };
            
          //   invoiceIssue(params)
          //     .then(res => {
          //       const data = res.data;
          //       const { urlQRCode } = data;
          //       uni.navigateTo({
          //         url: `/pages/parking/web_view/index?url=${encodeURIComponent(urlQRCode)}`,
          //       });
          //     })
          //     .catch(err => {
          //       console.error('开票失败:', err);
          //       uni.showToast({
          //         title: '开票失败，请重试',
          //         icon: 'none'
          //       });
          //     });
          // });
        }
      });
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
}

</script>

<style lang="scss">
.box {
  width: 700rpx;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #323232;
  margin-top: 30rpx;
  margin-bottom: 20rpx;
}

.box1 {
  width: 700rpx;
  margin: 0 auto;
}

.list {
  display: flex;
  align-items: center;
  justify-content: space-between;
  border: 1px solid rgba(255, 110, 0, 0.54);
  border-radius: 5px;
  padding: 20rpx;
  width: 100%;
  box-sizing: border-box;
  margin-top: 20rpx;
  background-color: #fff;
}

.list.selected {
  background-color: #FEF6EF;
}

.list .left {
  display: flex;
  align-items: center;
  flex-direction: row;
}

.list .left .img {
  width: 60rpx;
  height: 60rpx;
  margin-right: 10rpx;
}

.list .left .img image {
  width: 60rpx;
  height: 60rpx;
}

.list .left .text image {
  width: 30rpx;
  height: 30rpx;
  margin-left: 10rpx;
}

.list .left .text .p1 {
  font-size: 24rpx;
  font-weight: 400;
  color: #444;
}

.list .left .text .p2 {
  font-size: 48rpx;
  font-weight: 700;
  color: #444;
  margin: 10rpx 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.list .left .text .p3 {
  font-size: 24rpx;
  font-weight: 400;
  color: #444;
}

checkbox .wx-checkbox-input {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 3rpx solid rgba(255, 110, 0, 0.55);
}

checkbox .wx-checkbox-input.wx-checkbox-input-checked {
  border: none;
  background: #FF725C;
}

checkbox .wx-checkbox-input.wx-checkbox-input-checked::before {
  width: 40rpx;
  height: 40rpx;
  line-height: 40rpx;
  border-radius: 50%;
  text-align: center;
  font-size: 32rpx;
  color: #fff;
  background: transparent;
  transform: translate(-50%, -50%) scale(1);
}

.picker {
  width: 200rpx;
  height: 60rpx;
  line-height: 60rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  text-align: center;
  font-size: 28rpx;
}

.invoice-title-btn {
  font-size: 28rpx;
  color: #FF725C;
  margin-left: 20rpx;
}

.bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  box-sizing: border-box;
  background: #fff;
  z-index: 10;
  border-top: 1rpx solid #eee;
}

.bottom .p1 {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10rpx;
}

.bottom .p1 view {
  border: 1px solid #aaa;
  width: 110rpx;
  height: 48rpx;
  line-height: 48rpx;
  text-align: center;
  margin-left: 10rpx;
  font-size: 28rpx;
  border-radius: 4rpx;
}

.selected {
  color: #FF725C;
  border: 1px solid #FF725C !important;
}

.bottom .p2 {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.bottom .p2 .left {
  display: flex;
  align-items: center;
}

.bottom .p2 .left view {
  margin-left: 10rpx;
  color: #FF725C;
  font-size: 28rpx;
}

.bottom .p2 .button {
  border-radius: 6rpx;
  background: #FF725C;
  width: 200rpx;
  height: 68rpx;
  line-height: 68rpx;
  text-align: center;
  color: #fff;
  font-size: 28rpx;
}

.scroll-container {
  height: calc(100vh - 300rpx);
  overflow-y: auto;
  margin-bottom: 120rpx;
}

.pagination-container {
  margin-top: 20rpx;
  margin-bottom: 20rpx;
}
</style>